'use strict';

const path = require('path')
const pkgDir = require('pkg-dir').sync
const npminstall = require('npminstall')
const {
    pathExistsSync
} = require('path-exists')

const {
    isObject
} = require('@sue-cli-dev/utils')

const formatPath = require('@sue-cli-dev/format-path')
const {
    getDefaultRegistry,
    getNpmLatestVersion
} = require('@sue-cli-dev/get-npm-info')

class package {
    constructor(options) {
        if (!options) {
            throw new Error('Package类的options参数不能为空')
        }

        if (!isObject(options)) {
            throw new Error('Package类的options参数必须为对象')
        }
        // 路径
        this.targetPath = options.targetPath
        // 缓存路径
        this.storeDir = options.storeDir
        // 包名
        this.packageName = options.packageName
        // 版本
        this.packageVersion = options.packageVersion
    }

    async prepare() {
        if (this.packageVersion === 'latest') {
            this.packageVersion = await getNpmLatestVersion(this.packageName)
        }
    }

    // 判断当前Package是否存在
    async exists() {
        if (this.storeDir) {
            await this.prepare()
        } else {
            pathExistsSync(this.targetPath)
        }
    }

    // 安装Package
    async install() {
        await this.prepare()
        return npminstall({
            root: this.targetPath,
            storeDir: this.storeDir,
            registry: getDefaultRegistry(),
            pkgs: [{
                name: this.packageName,
                version: this.packageVersion
            }]
        })
    }

    // 更新Package
    update() {}

    // 获取入口文件路径
    getRootFilePath() {
        // 1、获取package.json所在目录
        const dir = pkgDir(this.targetPath)
        if (dir) {
            // 2、读取package.json
            const pkgFile = require(path.resolve(dir, 'package.json'))
            // 3、寻找main/lib
            if (pkgFile && (pkgFile.main || pkgFile.lib)) {
                // 4、路径的兼容
                return formatPath(path.resolve(dir, pkgFile.main))
            }
        }
        return null
    }
}

module.exports = package;
